<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;

/***
 *  数据库备份
 */
class BackUp extends Command
{
   /**
    * The name and signature of the console command.
    *
    * @var string
    */
   protected $signature = 'back:up';

   /**
    * The console command description.
    *
    * @var string
    */
   protected $description = 'backup description';

   protected $process;

   /**
    * Create a new command instance.
    *
    * @return void
    */
   public function __construct()
   {
      parent::__construct();

      $file_name = date('Y-m-d-H:i:s') . '-' . config('database.connections.mysql.database') . '.sql';
      $this->process = new Process(sprintf(
         'mysqldump -u%s -p%s %s > %s',
         config('database.connections.mysql.username'),
         config('database.connections.mysql.password'),
         config('database.connections.mysql.database'),
         storage_path('../../' . $file_name) //生成到项目文件夹外
      ));
   }

   /**
    * Execute the console command.
    *
    * @return mixed
    */
   public function handle()
   {
//      file_put_contents('/home/www/test123.log', date("Y-m-d H:i:s") . PHP_EOL, FILE_APPEND);  //测试写入
      try {
         $this->process->mustRun();

         $this->info('The backup has been proceed successfully.');
      } catch (ProcessFailedException $exception) {
         $this->error('The backup process has been failed.');
      }
   }

}
